<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use DB;

class LinkController extends Controller
{
    /*
		添加轮播
    */
	public function getAdd()
	{
		//解析模板
		return view('admin.link.add');
	}

	/*
		执行添加
	*/
	public function postInsert(Request $request)
	{
		
		$data =$request->except('_token');
		//判断链接名是否正确
		if(!preg_match('/[a-zA-z]+:\/\/[^\s]*/',$data['ladds'])){
			return back()->with('error','链接名不合法');
		}
		//图片添加
		$data['lpic'] = UserController::upload($request,'lpic','links');
		$data['regtime'] = time();
		//执行添加
		$res = DB::table('shop_links')->insert($data);
		if($res){
			return redirect('/admin/link/index')->with('success','链接添加成功');
		}else{
			return back()->with('error','链接添加失败');
		}
	}

	/*
		链接列表
	*/
	public function getIndex(Request $request)
	{
		$links = DB::table('shop_links')->get();
		
		// //解析模板
		return view('admin.link.index',['links'=>$links]);
	} 

	/*
		删除链接
	*/
	/*
		商品删除
	*/
	public function postDelete(Request $request)
	{
		//获取id
		$id = $request->input('id');

		//获取图片路径
		$path = DB::table("shop_links")->where('lid',$id)->value('lpic');
		//删除数据库
		$res = DB::table('shop_links')->where('lid',$id)->delete();
		//删除本地图片
		if(!empty($path)){
			$path = '.'.$path;
			if(file_exists($path)){
				unlink($path);
			}
		}
		//返回给ajax
		echo $res;
	}

	/*
		商品修改
	*/
	public function getEdit(Request $request)
	{
		
		$id = $request->input('id');
		//获取数据
		$links = DB::table('shop_links')->where('lid',$id)->first();
		//解析模板
		return view('admin.link.edit',['links'=>$links]);
	}

	/*
		执行修改
	*/
	public function postUpdate(Request $request)
	{
		$data = $request->except('_token');
		//判断图片是否上传
		if($request->hasFile('lpic')){
			$data['lpic'] = UserController::upload($request,'lpic','links');

		}

		$data['updtime'] = time(); 
		//执行添加
		$res = DB::table('shop_links')->where('lid',$request->input('lid'))->update($data);
		if($res){
			return redirect('/admin/link/index')->with('success','链接修改成功');
		}else{
			return back()->with('false','链接修改失败');
		}
	}

}
